package com.zhxs.nfcscan.view;

import static com.zhxs.websocket.RequestData.WEB_SOCKET_HEART_CLIENT;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;
import com.yc.ycthreadpoollib.PoolThread;
import com.zhhd.libdb.PatrolRecord;
import com.zhhd.libdb.ProjectDatabase;
import com.zhxs.nfcscan.R;
import com.zhxs.nfcscan.adapter.PatrolRecordAdapter;
import com.zhxs.nfcscan.base.app.AppActivity;
import com.zhxs.nfcscan.base.app.AppApplication;

import com.zhxs.nfcscan.base.http.entity.PersonInfo;
import com.zhxs.utils.LogUtil;
import com.zhxs.utils.ThreadPoolHelper;
import com.zhxs.websocket.RequestData;
import com.zhxs.websocket.WebSocketService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 巡更页面
 */
public class PatrolActivity extends AppActivity {

    private RecyclerView rvUnpatrolled;
    private RecyclerView rvPatrolled;
    private TextView tvUnpatrolledEmpty;
    private TextView tvPatrolledEmpty;
    private TextView tvNoDataTip;
    private Button btnSyncData;

    private PatrolRecordAdapter unpatrolledAdapter;
    private PatrolRecordAdapter patrolledAdapter;
    
    private List<PatrolRecord> allPatrolRecords = new ArrayList<>();
    private List<PatrolRecord> unpatrolledRecords = new ArrayList<>();
    private List<PatrolRecord> patrolledRecords = new ArrayList<>();
    private MMKV mmkv;
    private String serverUrl;
    private NfcAdapter nfcAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol;
    }

    @Override
    protected void initView() {
        rvUnpatrolled = findViewById(R.id.rv_unpatrolled);
        rvPatrolled = findViewById(R.id.rv_patrolled);
        tvUnpatrolledEmpty = findViewById(R.id.tv_unpatrolled_empty);
        tvPatrolledEmpty = findViewById(R.id.tv_patrolled_empty);
        tvNoDataTip = findViewById(R.id.tv_no_data_tip);
        btnSyncData = findViewById(R.id.btn_sync_data);

        // 设置RecyclerView
        setupRecyclerViews();
        
        // 设置点击事件
        btnSyncData.setOnClickListener(v -> {
            Intent intent = new Intent(this, DataSyncActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected void initData() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        mmkv = MMKV.defaultMMKV();
        // 获取服务器地址
        serverUrl = mmkv.decodeString(AppApplication.KEY_SERVER_URL, AppApplication.DEFAULT_SERVER_URL);


    }

    @Override
    protected void onResume() {
        super.onResume();
        // 启用NFC前台调度
        Intent intent = new Intent(PatrolActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(PatrolActivity.this, 0, intent, 0);
        nfcAdapter.enableForegroundDispatch(PatrolActivity.this, pendingIntent, null, null);

        // 加载巡更数据
        loadPatrolData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 禁用NFC前台调度
        nfcAdapter.disableForegroundDispatch(PatrolActivity.this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 处理NFC标签
        handleNfcIntent(intent);
    }

    /**
     * 设置RecyclerView
     */
    private void setupRecyclerViews() {
        // 未巡更列表
        rvUnpatrolled.setLayoutManager(new LinearLayoutManager(this));
        unpatrolledAdapter = new PatrolRecordAdapter(this, unpatrolledRecords);
        rvUnpatrolled.setAdapter(unpatrolledAdapter);

        // 已巡更列表
        rvPatrolled.setLayoutManager(new LinearLayoutManager(this));
        patrolledAdapter = new PatrolRecordAdapter(this, patrolledRecords);
        rvPatrolled.setAdapter(patrolledAdapter);
    }

    private static final int REFRESH_REFRESH_WHAT = 999;
    private Handler mHeartHandler = new Handler(new HeartCallback());

    private class HeartCallback implements Handler.Callback{
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == REFRESH_REFRESH_WHAT){
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (allPatrolRecords!=null && !allPatrolRecords.isEmpty()){
//                            updateUI();
//                        }else {
//                            showEmptyState();
//                        }
//                    }
//                });
                if (allPatrolRecords!=null && !allPatrolRecords.isEmpty()){
                    updateUI();
                }else {
                    showEmptyState();
                }

            }
            return false;
        }
    }

    /**
     * 加载巡更数据
     */
    private void loadPatrolData() {

        PoolThread executor = ThreadPoolHelper.Companion.get().getExecutor();
        executor.setName("巡更计划load成功");
        executor.execute(new Runnable() {
            @Override
            public void run() {
                unpatrolledRecords.clear();
                patrolledRecords.clear();
                allPatrolRecords.clear();
                // 未巡更
                List<PatrolRecord> unPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().loadUnPatrolRecord();
                unpatrolledRecords.addAll(unPatrolRecord);
                LogUtil.d("未巡更记录："+ unPatrolRecord.size());
                // 已经巡更
                List<PatrolRecord> hasPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().loadHasPatrolRecord();
                patrolledRecords.addAll(hasPatrolRecord);

                List<PatrolRecord> allPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().getAllPatrolRecord();
                allPatrolRecords.addAll(allPatrolRecord);

                mHeartHandler.sendEmptyMessage(REFRESH_REFRESH_WHAT);
            }
        });

    }

    /**
     * 更新UI
     */
    private void updateUI() {
        // 更新未巡更列表
        unpatrolledAdapter.updateData(unpatrolledRecords);
        tvUnpatrolledEmpty.setVisibility(unpatrolledRecords.isEmpty() ? View.VISIBLE : View.GONE);

        // 更新已巡更列表
        patrolledAdapter.updateData(patrolledRecords);
        tvPatrolledEmpty.setVisibility(patrolledRecords.isEmpty() ? View.VISIBLE : View.GONE);

        // 显示总体提示
        tvNoDataTip.setVisibility(allPatrolRecords.isEmpty() ? View.VISIBLE : View.GONE);
    }

    /**
     * 显示空状态
     */
    private void showEmptyState() {
        unpatrolledRecords.clear();
        patrolledRecords.clear();
        allPatrolRecords.clear();
        updateUI();
    }

    /**
     * 处理NFC Intent
     */
    private void handleNfcIntent(Intent intent) {
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {

            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                String cardId = bytesToHexString(tag.getId());
                LogUtil.d("读取到NFC卡ID: " + cardId);
                
                // 检查是否有对应的未巡更记录
                checkAndUpdatePatrolRecord(cardId);
            }
        }
    }

    /**
     * 检查并更新巡更记录
     */
    private void checkAndUpdatePatrolRecord(String cardId) {
        PatrolRecord matchedRecord = null;
        for (PatrolRecord record : unpatrolledRecords) {
            if (cardId!=null && !TextUtils.isEmpty(record.getPatrolPointId())){
                if (cardId.toLowerCase().equals(record.getPatrolPointId().toLowerCase())) {
                    matchedRecord = record;
                    break;
                }
            }

        }

        if (matchedRecord != null) {
            // 找到匹配的记录，更新为已巡更
            updatePatrolRecord(matchedRecord);
        } else {
            Toast.makeText(PatrolActivity.this, "未找到对应的巡更点，请检查卡片是否正确" , Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新巡更记录 数据未更新 要修改
     */
    private void updatePatrolRecord(PatrolRecord record) {
        // 获取当前时间
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                .format(new Date());

        // 获取持机人信息
        String userInfoJson = mmkv.decodeString(AppApplication.KEY_PERSON_INFO, "");
        if (!TextUtils.isEmpty(userInfoJson)) {
            try {
                PersonInfo personInfo = new Gson().fromJson(userInfoJson, PersonInfo.class);
                if (personInfo != null) {
                    // 更新记录
                    record.setPatrolPersonId(personInfo.getUserId());
                    record.setPatrolPersonName(personInfo.getUserName());

                    record.setPatrolDeptName(personInfo.getDeptName());
                    record.setPatrolTime(currentTime);
                    //通过时间去计算巡更标志
                    record.setPatrolStatus(calculatePatrolStatus(record.getPlanTimeStart(), record.getPlanTimeEnd(), currentTime));

                    PoolThread executor = ThreadPoolHelper.Companion.get().getExecutor();
                    executor.setName("巡更计划load成功");
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().updatePatrolRecord(record);
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            unpatrolledRecords.clear();
                            patrolledRecords.clear();
                            allPatrolRecords.clear();

                            // 未巡更
                            List<PatrolRecord> unPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().loadUnPatrolRecord();
                            unpatrolledRecords.addAll(unPatrolRecord);
                            LogUtil.d("未巡更记录："+ unPatrolRecord.size());
                            // 已经巡更
                            List<PatrolRecord> hasPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().loadHasPatrolRecord();
                            patrolledRecords.addAll(hasPatrolRecord);

                            List<PatrolRecord> allPatrolRecord = ProjectDatabase.getInstance(PatrolActivity.this).getPatrolRecordDao().getAllPatrolRecord();
                            allPatrolRecords.addAll(allPatrolRecord);

                            mHeartHandler.sendEmptyMessage(REFRESH_REFRESH_WHAT);

                            Toast.makeText(PatrolActivity.this, "巡更成功！地点: " + record.getPatrolPointName() , Toast.LENGTH_SHORT).show();
                            LogUtil.d("巡更成功: " + record.getPatrolPlanName() + " - " + record.getPatrolPointName());
                        }
                    });

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void filterData() {

    }



    /**
     * 计算巡更状态
     * @param planTimeStart 计划开始时间
     * @param planTimeEnd 计划结束时间
     * @param patrolTime 实际打卡时间
     * @return 巡更状态：1-正常巡更，3-晚巡，4-早巡
     */
    private int calculatePatrolStatus(String planTimeStart, String planTimeEnd, String patrolTime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            
            Date startTime = sdf.parse(planTimeStart);
            Date endTime = sdf.parse(planTimeEnd);
            Date actualTime = sdf.parse(patrolTime);
            
            if (startTime == null || endTime == null || actualTime == null) {
                LogUtil.e("时间解析失败: start=" + planTimeStart + ", end=" + planTimeEnd + ", actual=" + patrolTime);
                return 0;
            }
            
            // 比较时间
            if (actualTime.before(startTime)) {
                // 早巡
                LogUtil.d("早巡: 打卡时间 " + patrolTime + " 早于计划开始时间 " + planTimeStart);
                return 4;
            } else if (actualTime.after(endTime)) {
                // 晚巡
                LogUtil.d("晚巡: 打卡时间 " + patrolTime + " 晚于计划结束时间 " + planTimeEnd);
                return 3;
            } else if (actualTime.after(startTime) && startTime.before(endTime)){
                // 正常巡更（在计划时间内）
                LogUtil.d("正常巡更: 打卡时间 " + patrolTime + " 在计划时间范围内");
                return 1;
            }else {
                return 0;
            }
            
        } catch (ParseException e) {
            LogUtil.e("时间解析异常: " + e.getMessage());
            e.printStackTrace();
            return 0; // 解析失败时默认正常巡更
        }
    }

    /**
     * 字节数组转十六进制字符串
     */
    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}



